package com.vains.exception;

import com.netflix.client.ClientException;
import com.netflix.zuul.exception.ZuulException;
import com.vains.system.model.Result;
import com.vains.system.util.ResultUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpServerErrorException;

/**
 * 全局异常处理类
 * @author vains
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理
     * @param e 异常信息
     * @return Result
     */
    @ExceptionHandler(CustomerException.class)
    public Result<String> customerException(CustomerException e) {
        return ResultUtils.error(e.getMessage());
    }

    /**
     * org.springframework.util.Assert 中的异常处理
     * @param e 异常信息
     * @return Result
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> illegalArgumentException(IllegalArgumentException e) {
        return ResultUtils.error(e.getMessage());
    }

    /**
     * 捕获 参数绑定 异常
     * @param e 异常信息
     * @return 统一返回体
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> httpMessageNotReadableException(HttpMessageNotReadableException e) {
        return ResultUtils.error("参数绑定失败,请检查参数后重试!");
    }

    /**
     * 捕获 请求方式错误 异常
     * @param e 异常信息
     * @return 统一返回体
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return ResultUtils.error("请求方式有误：" + e.getMessage());
    }

    /**
     * 捕获 Feign远程调用 异常
     * @param e 异常信息
     * @return 统一返回体
     */
    @ExceptionHandler(ClientException.class)
    public Result<String> clientException(ClientException e) {
        return ResultUtils.error(e.getErrorMessage());
    }

    /**
     * 捕获 网关转发 异常
     * @param e 异常信息
     * @return 统一返回体
     */
    @ExceptionHandler(ZuulException.class)
    public Result<String> zuulException(ZuulException e) {
        return ResultUtils.error("密码错误,请检查密码是否正确!");
    }

    /**
     * 捕获 remoteTokenService调用 异常
     * @param e 异常信息
     * @return 统一返回体
     */
    @ExceptionHandler(HttpServerErrorException.class)
    public Result<String> zuulException(HttpServerErrorException e) {
        return ResultUtils.error(e.getMessage());
    }

    /**
     * 捕获 除以上异常之外的 异常
     * @param e 异常信息
     * @return 统一返回体
     */
    @ExceptionHandler(Exception.class)
    public Result<String> Exception(Exception e) {
        return ResultUtils.error(e.getMessage());
    }

}
